package br.com.locadoracom.managedBeam;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

import br.com.locadoracom.dao.MidiaDao;
import br.com.locadoracom.model.Midia;
import br.com.locadoracom.model.TipoMidia;

@ManagedBean
@ViewScoped
public class EditMidiaMB implements Serializable  {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Midia midia;
	private TipoMidia tipoMidia;
	private TipoMidia[] tipoMidias;
	private MidiaDao midiaDao;
	
	public EditMidiaMB() {
		midia = new Midia();
	}
	
	public Midia getMidia() {
		return midia;
	}
	public void setMidia(Midia midia) {
		this.midia = midia;
	}
	public TipoMidia[] getTipoMidias() {
		tipoMidias = TipoMidia.values();
		return tipoMidias;
	}
	public void setTipoMidias(TipoMidia[] tipoMidias) {
		this.tipoMidias = tipoMidias;
	}
	public TipoMidia getTipoMidia() {
		return tipoMidia;
	}
	public void setTipoMidia(TipoMidia tipoMidia) {
		this.tipoMidia = tipoMidia;
	}
	
	public void carrega(AjaxBehaviorEvent event){
		midiaDao = new MidiaDao();
		midia = midiaDao.procurarPorTipo(tipoMidia);
		if (midia==null)
			midia = new Midia();
	}
	
	public String salvarEditar(){
		FacesContext fc = FacesContext.getCurrentInstance();
		midiaDao = new MidiaDao();
		
		midia.setTipoMidia(tipoMidia);
		midia = midiaDao.merge(midia);
			
		fc.addMessage(null , new FacesMessage("Midia cadastrada com sucesso."));
		fc.getExternalContext().getSessionMap().put("idNovaMidia", midia);
		
		return "viewEditMidia";
	}
}